package com.cjl.demo.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>Description: 对业务写方法加锁、对业务读方法不加锁、容易产生脏读问题</p>
 *
 * @ uthor chenjinliang
 * @ date: 2020/5/22
 */
public class Demo08 {
    String name;
    double balance;
    public synchronized void set(String name, double balance){
        this.name = name;
        try {
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.balance = balance;
    }
    public /**synchronized*/ double getBalance(String name){
        return this.balance;
    }

    /**
     * 2.对业务写方法加锁，同时也要对业务读方法加锁，否则容易产生脏读问题
     * @param args
     */
    public static void main(String[] args) {
        splitString("abcd");
        Demo08 demo08 = new Demo08();
        new Thread(()->demo08.set("zhangsan",100.0)).start(); //JDK1.8新特性
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(demo08.getBalance("zhangsan"));
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(demo08.getBalance("zhangsan"));
    }

    public static List<String> splitString(String input){
//        if(StringUtil.isBlank(input)){
//            return Collections.emptyList();
//        }
        List<String> result = new ArrayList();
        for(int i = 0; i < input.length(); i ++){
            for(int j = i; j < input.length(); j++){
                result.add(input.substring(i, j));
            }
        }
        return result;
    }
}
